//
//  MyViewController.m
//  接口测试
//
//  Created by 叶子韬韬 on 2017/4/16.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

#import "MyViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "HeadView.h"
@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)UITableView *table;

@property(nonatomic, strong)HeadView *header;
@property(nonatomic,strong)UIImageView *backgroundImgV;//背景图
@property(nonatomic,assign)float backImgHeight;
@property(nonatomic,assign)float backImgWidth;
@property(nonatomic,assign)float backImgOrgy;
@end

@implementation MyViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.view.backgroundColor = UIColor.whiteColor;
    
    [self lashenBgView];
    [self initView];
    [self buttonMethods];
    
    
    
    
}
//拉伸顶部图片
-(void)lashenBgView{
    UIImage *image=[UIImage imageNamed:@"bg-mine.png"];
    //图片的宽度设为屏幕的宽度，高度自适应
    NSLog(@"%f",image.size.height);
    _backgroundImgV=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 230)];
    _backgroundImgV.image=image;
    _backgroundImgV.userInteractionEnabled=YES;
    [self.view addSubview:_backgroundImgV];
    _backImgHeight=_backgroundImgV.frame.size.height;
    _backImgWidth=_backgroundImgV.frame.size.width;
    _backImgOrgy=_backgroundImgV.frame.origin.y;
}



#pragma mark -- initView
-(void)initView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGBCOLOR(211, 211, 211);
    
    
    self.header = [[HeadView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 230)];
    
    //init table
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT-49) style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.backgroundColor = [UIColor clearColor];
    self.table.tableHeaderView = self.header;
    [self.view addSubview:self.table];
}
#pragma mark -- headerView button's Methods
-(void)buttonMethods{
    //block button.tag
    __weak __typeof(self)weakSelf = self;
    self.header.action = ^(NSInteger tag){
        [weakSelf touchMethod:tag];
    };
}
#pragma mark -- table delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *titleArray = @[@"优惠券",@"地址管理"];
    NSArray *imgArray = @[@"me_preferential",@"me_address"];
    static NSString *cellid = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellid];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = RGBACOLOR(51, 51, 51, 1);
    }
    cell.textLabel.text = titleArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:imgArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {//优惠券
        
    }
    if (indexPath.row == 1) {//地址管理
    }
}

#pragma mark -- btn tag值    icon:200  userInformation:201 设置:202
#pragma mark -- 订单btn tag值 全部订单:100 待付款:101 完成订单:102
-(void)touchMethod:(NSInteger)tag{
    if (tag == 20) {//点击头像

        [self updateIcon];
        
    }
    if (tag == 21) {//设置
        
    }
    if (tag == 22) {//全部订单
       
    }
    if (tag == 23) {//待付款订单
        
    }
    if (tag == 24) {//已完成订单
        
    }
}


#pragma mark -- 上传头像
-(void)updateIcon{
    UIImagePickerController *choseFromLibrary = [[UIImagePickerController alloc]init];
    choseFromLibrary.delegate = self;
    choseFromLibrary.allowsEditing = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择头像" message:@"请上传您的头像" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *chooseFromAlbum = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        choseFromLibrary.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:choseFromLibrary animated:YES completion:nil];
    }];
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        choseFromLibrary.sourceType =  UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:choseFromLibrary animated:YES completion:nil];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:chooseFromAlbum];
    [alert addAction:takePhoto];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark -- imagePickControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];//拿到图片原画
    [self.header.iconBtn setImage:[resultImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:0];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
    [HttpUtils upLoadFileWith:resultImage WithSuccess:^(id str) {
        
    } andFailBack:^(id str) {
        
    }];
}


//当scrollView开始滚动的时候 对头部背景fram重新计算
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int contentOffsety = scrollView.contentOffset.y;
    if (contentOffsety<0) {
        CGRect rect = _backgroundImgV.frame;
        rect.size.height = _backImgHeight-contentOffsety;
        rect.size.width = _backImgWidth* (_backImgHeight-contentOffsety)/_backImgHeight;
        rect.origin.x =  -(rect.size.width-_backImgWidth)/2;
        rect.origin.y = 0;
        _backgroundImgV.frame = rect;
    }else{
        CGRect rect = _backgroundImgV.frame;
        rect.size.height = _backImgHeight;
        rect.size.width = _backImgWidth;
        rect.origin.x = 0;
        rect.origin.y = -contentOffsety;
        _backgroundImgV.frame = rect;
        
    }
    
}




-(void)downloadPriture{
     NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
    filePath = [NSString stringWithFormat:@"%@/%@",filePath,@"xifu.jpg"];
    NSLog(@"%@",filePath);
    
    // 确定请求的URL
    NSURL *url = [NSURL URLWithString:@"Http://localhost:8088/day10/download?name=xifu.JPG"];
    
    //创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSessionDownloadTask *task =[manger downloadTaskWithRequest:request
                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                return [NSURL fileURLWithPath:filePath];
                            }
                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                       if (error) {
                           NSLog(@"%@",error.description);
                       }else{
                           NSData *data = [NSData dataWithContentsOfURL:filePath];
                           
                           NSLog(@"%@",data);
                           
                          
                       }

                   }];
    [task resume];
    
    
    
}

@end
